package com.ng.framework.view.desktop;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextField;

import com.ng.framework.persistence.NGGenericPersistence;

public abstract class NGEntitySelectorField<T, P extends NGGenericPersistence<T>> extends JPanel
		implements
			ActionListener,
			MouseListener {

	private static final long serialVersionUID = -4096420832431625398L;

	private JTextField textField;
	private JButton buttonSelect;
	private JButton buttonDeselect;
	protected NGEntitySelectorDialog<T, P> ngEntitySelectorDialog;

	private T entity;

	public NGEntitySelectorField() {
		this.textField = new JTextField();
		this.textField.addMouseListener(this);
		this.buttonSelect = NGGUIUtils.createIconButton("icons/search.png", this);
		this.buttonDeselect = NGGUIUtils.createIconButton("icons/cross.png", this);
		this.buildGui();
	}

	private void buildGui() {
		this.setLayout(new GridBagLayout());

		this.add(textField, new GridBagConstraints(0, 0, 1, 1, 1, 0, GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL,
				new Insets(0, 0, 0, 0), 0, 0));
		this.add(buttonSelect, new GridBagConstraints(1, 0, 1, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE,
				new Insets(0, 0, 0, 0), 0, 0));
		this.add(buttonDeselect, new GridBagConstraints(2, 0, 1, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE,
				new Insets(0, 0, 0, 0), 0, 0));
	}

	public abstract void select();

	public void deselect() {
		this.entity = null;
		this.textField.setText("");
	}

	public abstract void edit();

	public T getEntity() {
		return entity;
	}

	public void setEntity(T entity) {
		this.entity = entity;
		this.textField.setText(entity != null ? entity.toString() : "");
		if (ngEntitySelectorDialog != null) {
			this.ngEntitySelectorDialog.dispose();
		}

	}

	@Override
	public void mouseClicked(MouseEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mousePressed(MouseEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseReleased(MouseEvent e) {
		this.edit();

	}

	@Override
	public void mouseEntered(MouseEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseExited(MouseEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == buttonSelect) {
			this.select();

		} else if (e.getSource() == buttonDeselect) {
			this.deselect();
		}

	}
}
